package com.huige.wiki.controller;

import com.alibaba.fastjson.JSONObject;

import com.huige.wiki.req.UserLoginReq;
import com.huige.wiki.req.UserQueryReq;
import com.huige.wiki.req.UserResetPasswordReq;
import com.huige.wiki.req.UserSaveReq;
import com.huige.wiki.resp.PageResp;
import com.huige.wiki.resp.UserLoginResp;
import com.huige.wiki.resp.UserQueryResp;
import com.huige.wiki.service.UserService;
import com.huige.wiki.util.Result;
import com.huige.wiki.util.SnowFlake;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Api(tags ="用户管理相关接口")
public class UserController {

    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @Resource
    private SnowFlake snowFlake;

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    @ApiOperation("查询用户列表")
    @GetMapping("/list")
    public Result<PageResp<UserQueryResp>> list(@Valid UserQueryReq req){
        return Result.success(userService.list(req));
    }

    @ApiOperation("保存用户（新增或修改）")
    @PostMapping("/save")
    public Result save(@Valid @RequestBody UserSaveReq req){
        // 密码两层加密：前端会进行md5一次，后端会再次基于前端的md5再次md5
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        userService.save(req);
        return Result.success();
    }


    // 删除
    @ApiOperation("删除用户")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id){
        userService.delete(id);
        return Result.success();
    }

    // 更改用户密码
    @ApiOperation("修改用户密码")
    @PostMapping("/reset-password")
    public Result resetPassword(@Valid @RequestBody UserResetPasswordReq req){
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        userService.resetPassword(req);
        return Result.success();
    }

    // 用户登录
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<UserLoginResp> login(@Valid @RequestBody UserLoginReq req){
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        UserLoginResp userLoginResp = userService.login(req);
        return Result.success(userLoginResp);
    }

    // 退出登录
    @ApiOperation("退出登录")
    @GetMapping("/logout/{token}")
    public Result logout(@PathVariable String token) {
        redisTemplate.delete(token);
        return Result.success();
    }
}
